package com.kara.woodAgent.web.ws;

import com.kara.woodAgent.web.user.model.vo.LoginVo;
import io.vertx.core.http.ServerWebSocket;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketConnectManager {


    private final ConcurrentHashMap<String, ConnectionWrapper> instances = new ConcurrentHashMap<>();
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    @PostConstruct
    public void init() {
        //😃

        executor.schedule(() -> {
            LocalDateTime now = LocalDateTime.now();
            for (Map.Entry<String, ConnectionWrapper> entry : instances.entrySet()) {
                ConnectionWrapper connectionWrapper = entry.getValue();
                //超过30分钟没有消息，关闭连接
                if (!connectionWrapper.using && connectionWrapper.getLastMessageTime().isBefore(now.minusMinutes(30))) {
                    //关闭
                    connectionWrapper.close();
                }
            }

        }, 10, TimeUnit.SECONDS);

    }

    public void addConnection(LoginVo loginVo, String token, ServerWebSocket serverWebSocket) {

        ConnectionWrapper connectionWrapper = instances.put(loginVo.getId() + "_" + token, new ConnectionWrapper(serverWebSocket, loginVo.getId(), token));

        if (connectionWrapper != null) {
            //关闭老的
            connectionWrapper.close();
        }
    }

    @Data
    public class ConnectionWrapper {
        //WEBSOCKET 连接
        private ServerWebSocket serverWebSocket;


        private LocalDateTime lastMessageTime;

        private Long userId;

        private String token;

        private volatile boolean using;

        public ConnectionWrapper(ServerWebSocket serverWebSocket, Long userId, String token) {
            this.serverWebSocket = serverWebSocket;
            this.userId = userId;
            this.token = token;
            lastMessageTime = LocalDateTime.now();

            this.serverWebSocket
                    .textMessageHandler(message -> {
                        log.info("【Vertx-Websocket-Server】 => 收到消息：{}", message);
                    })
                    .closeHandler(v -> {
                        //将自己在集合中移除
                        log.error("【Vertx-Websocket-Server】 => 断开连接");
                        WebSocketConnectManager.this.instances.remove(userId + "_" + token);
                    })
                    .exceptionHandler(err -> {
                        log.error("【Vertx-Websocket-Server】 => 错误信息：{}", err.getMessage(), err);
                    });


        }

        public void close() {
            if (serverWebSocket != null && !serverWebSocket.isClosed()) {
                serverWebSocket.close();
            }
        }

        public void writeMessage(String message) {

            if (serverWebSocket != null && !serverWebSocket.isClosed()) {
                serverWebSocket.writeTextMessage(message);
            }
        }
    }

}
